package org.noip.milhous.clause;

import java.lang.reflect.Method;

import org.noip.milhous.DatastoreObject;
import org.noip.milhous.FieldName;
import org.noip.milhous.SQLInterface;
import org.noip.milhous.annotations.databaseFieldName;

public abstract class Utilities
{
	/**
	 * Helper function to take an object and get the sql version out of it
	 * 
	 * @param item
	 * @return
	 */
	public String getInternal(Object item)
		{
			String result = null;

			String fname = getField(item);
			if (!fname.isEmpty())
				{
					result = fname;
				}
			else if (item != null)
				{
					result = item.toString();
				}
			else
				{
					result = "";
				}

			return result;
		}

	public static String getField(Object o)
		{
			String result = "";
			if (o instanceof FieldName)
				{
					result = ((FieldName) o).getDatabaseFieldName();
				}
			else if (o instanceof SQLInterface)
				{
					result = ((SQLInterface) o).toInternalSQL();
				}
			else
				{
					for (Method m : DatastoreObject.getListOfMethods(o.getClass()))
						{
							if (m.getAnnotation(databaseFieldName.class) != null)
								{
									try
										{
											result = m.invoke(o).toString();
										}
									catch (Exception e)
										{
											e.printStackTrace();
										}
								}
						}
				}
			return result;
		}

	/**
	 * do a smart quote an a string
	 * 
	 * @param s
	 *           the string to quote
	 * @return a string with one set of quotes around it
	 */
	public static String quoteString(String s)
		{
			if (s.charAt(0) != '`')
				{
					s = "`" + s + "`";
				}
			return s;
		}
}
